package com.zxp.utils.logUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Utility class for logging error messages to a file.
 */
public class ErrorLogger {

    private static final String LOG_FILE_PATH = "error_log.txt";

    /**
     * Logs an error message to the error log file.
     *
     * @param errorMessage The error message to be logged.
     */
    public static void logError(String errorMessage) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(LOG_FILE_PATH, true))) {
            // 获取当前时间
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = dateFormat.format(new Date());

            // 写入错误信息和时间戳到日志文件
            writer.println("[" + timestamp + "] " + errorMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // Example usage:
        try {
            // Simulate an error
            int result = 10 / 0;
        } catch (Exception e) {
            // Log the error
            logError("Error occurred: " + e.getMessage());
        }
    }
}
